#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

'''
mpyburn

Example:

    python3 mpytools/mpyburn.py -d /dev/ttyUSB0 --path ./build/

'''

import os
import pyboard


class MPYBurn(object):
    def __init__(self, device="/dev/ttyUSB0", baud=115200) -> None:
        self._device = device
        self._baud = baud

    def _burn(self, burn_path, dst_path: str = "/"):
        '''烧录'''
        for file in os.listdir(burn_path):
            # 当前文件或文件夹路径
            target = os.path.join(burn_path, file)

            if os.path.isdir(target):
                dest_dir = os.path.join(dst_path, file)
                print("mkdir :{}".format(dest_dir))
                try:
                    self._pyb.fs_mkdir(dest_dir)
                except:
                    pass
                self._burn(target, dest_dir)

            if os.path.isfile(target):
                # 复制文件
                dst_file = os.path.join(dst_path, file).replace('\\', '/')
                print("cp {} :{}".format(target, dst_file))
                self._pyb.fs_put(target, "{}".format(dst_file))

    def burn(self, burn_path, dst_path: str = "/"):
        self._pyb = pyboard.Pyboard(self._device, baudrate=int(self._baud))
        self._pyb.enter_raw_repl()
        self._burn(burn_path, dst_path)
        self._pyb.exit_raw_repl()
        self._pyb.close()


def main():
    import argparse

    cmd_parser = argparse.ArgumentParser(description="")
    cmd_parser.add_argument(
        "-d", "--device", type=str,
        default=os.environ.get("DEFAULT_DEVICE", "/dev/ttyUSB0"),
        help="serial device",
    )
    cmd_parser.add_argument(
        "-b", "--baudrate", type=int,
        default=os.environ.get("DEFAULT_BAUDRATE", "115200"),
        help="the baud rate of the serial device",
    )
    cmd_parser.add_argument(
        "--path", type=str,
        help="target",
    )

    args = cmd_parser.parse_args()

    # print(args)

    mpyburn = MPYBurn(device=args.device, baud=args.baudrate)

    mpyburn.burn(args.path)


if __name__ == "__main__":
    main()
